package hxgo

import (
	"net/http"
	"path"
	"strings"
	"mime/multipart"
)

// request object
type Request struct {
	Raw *http.Request
	Param      []string
	Url        string
	Method     string
	Host       string
	Uri        string
	RemoteAddr string
	TLS        bool
	Ip         string
	UserAgent  string
	Refer      string
	Suffix     string
}

// init request, fill properties
func (this *Request) init() {
	this.Url = this.Raw.URL.Path
	this.Method = this.Raw.Method
	this.Host = this.Raw.URL.Host
	this.Uri = this.Raw.RequestURI
	this.RemoteAddr = this.Raw.RemoteAddr
	this.TLS = this.Raw.TLS == nil
	this.Ip = strings.Split(this.Raw.RemoteAddr, ":")[0]
	this.UserAgent = this.Raw.UserAgent()
	this.Refer = this.Raw.Referer()
	this.Suffix = path.Ext(this.Url)
}

// get request header
func (this *Request) Header(key string) string {
	return this.Raw.Header.Get(key)
}

// get request cookie value
func (this *Request) Cookie(name string) string {
	c, e := this.Raw.Cookie(name)
	if e != nil {
		return ""
	}
	return c.Value
}

// check isAjax request
func (this *Request) IsAjax() bool {
	return this.Header("X-Requested-With") == "XMLHttpRequest"
}

// get uploaded file by key string
func (this *Request) File(key string) (multipart.File, *multipart.FileHeader, error) {
	this.Raw.ParseMultipartForm(32<<20)
	return this.Raw.FormFile(key)
}

// create new request object
func NewRequested(r *http.Request) *Request {
	req := &Request{Raw:r}
	req.init()
	return req
}


